<template>
  <div class="receptacle">
    <div>
      <a-button class="buutton">
        <icon-refresh/>
      </a-button>
      <a-button class="buutton">
        <icon-caret-left/>
      </a-button>
      <a-button class="buutton" @click="playStatus">
        <icon-pause-circle v-if="!play"/>
        <icon-right-circle v-else/>
      </a-button>
      <!--      <a-button class="buutton"></a-button>-->
      <a-button class="buutton">
        <icon-caret-right/>
      </a-button>
      <a-button class="buutton">
        <icon-heart/>
      </a-button>
    </div>
    <div class="container_center">
      <audio
          ref="audioRef"
          :src="data.url"
          autoplay
          @canplay="getDuration"
          @timeupdate="asss"
      >

      </audio>
      <span>{{ currenttime }}</span>
      <a-slider :format-tooltip="marks" :max="totalDuration" :model-value="CuterTimer" :style="{ width: '200px' }"
                @change="schedule"/>
      <span>{{ lastName }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, watch} from "vue"
import {getmusicUrlApi, getLyricApi} from "~/commonApi/api"
import {debounce} from "~/uilti/tool"
import {useStore} from "vuex";

const stroe = useStore()
const audioRef = ref(null)
const play = ref(false)
const lastName = ref(0.00)
const currenttime = ref(0.00)
const props = defineProps(['id', 'volumesize'])
const id = ref('')
const data = ref([])
watch(() => props.id, (newvalue, oldValue) => {
  id.value = newvalue
  console.log(newvalue, 'newvalue')
  musicUrl()
})
//监视传过来的音量变化赋值
watch(() => props.volumesize, (newvalue, oldValue) => {
  audioRef.value.volume = newvalue / 100
  console.log(audioRef.value.volume, ' audioRef.value.volume')
})
//监视stroe的歌曲是否变化
watch(() => stroe.state.playing, (newvalue, oldValue) => {
  setTimeout(() => {
    play.value = isStatus()
  }, 500)
}, {deep: true})


const musicUrl = async () => {
  const res = await getmusicUrlApi(id.value)
  const resQLT = await getLyricApi(id.value)
  let luric = resQLT.lrc.lyric
  getWord(luric)
  data.value = res.data[0]
}

//当前正在播放的进度时间戳
const CuterTimer = ref(0)
onMounted(() => {
  audioRef.value.ontimeupdate = function () {
    CuterTimer.value = audioRef.value.currentTime
    currenttime.value = hs(parseInt(audioRef.value.currentTime))
  };
  play.value = isStatus()
  console.log(play.value, ' play.value')

})
//检查歌曲处于是什么状态
const isStatus = () => {
  return audioRef.value.paused
}


// 获取歌曲总时长的时间戳
const totalDuration = ref(0)
const getDuration = () => {
  totalDuration.value = Math.round(audioRef.value.duration)
  lastName.value = Math.round(audioRef.value.duration);
  lastName.value = hs(lastName.value)
};

//控制提示显示内容
const marks = () => {
  return (CuterTimer.value / totalDuration.value).toFixed(1) * 100 + '%'

}

//处理歌词
const getWord = async (lyric) => {
  let tempArr = lyric.match(/\[(.*?):(.*?)\](.*?)\n/g);
  let arr = [];
  for (let temp of tempArr) {
    //对每一行进行拆分得到每一行中各个数据
    let tempItem = temp.match(/\[(.*?):(.*?)\](.*?)\n/);
    //将拆分好的数据push到新的数组中
    arr.push({
      time: timeEvent(tempItem[1] + ":" + tempItem[2]),
      str: tempItem[3],
    });
  }

  arr.forEach((v, i, arr) => { // 处理歌词为空
    if (v.str === '') {
      arr.splice(i, 1)
    }
  })
  stroe.commit('SERLYRIC', arr)
  return arr;
}

function timeEvent(e) {
  let time = e;
  let len = time.split(':');
  if (len.length == 3) {
    let hour = time.split(':')[0];
    let min = time.split(':')[1];
    let sec = time.split(':')[2];
    return Number(hour * 3600) + Number(min * 60) + Number(sec);
  }
  if (len.length == 2) {
    let min = time.split(':')[0];
    let sec = time.split(':')[1];
    return Number(min * 60) + Number(sec);
  }
  if (len.length == 1) {
    let sec = time.split(':')[0];
    return Number(sec);
  }
}


play.value = audioRef.value?.paused
const emit = defineEmits(['playPause'])
const playStatus = () => {

  if (audioRef.value.paused) {
    emit('playPause', 0)
    audioRef.value.play()
    play.value = false
  } else {
    emit('playPause', 1)
    audioRef.value.pause()
    play.value = true
  }

}
//歌曲进度条（推拽）

const schedule = (e) => {

  debounce(() => {
    CuterTimer.value = e
    audioRef.value.currentTime = e

  }, 100)

}


//秒数转换分+秒
const hs = (s) => {
  let h;
  h = Math.floor(s / 60);
  s = s % 60;
  h += "";
  s += "";
  h = (h.length == 1) ? "0" + h : h;
  s = (s.length == 1) ? "0" + s : s;
  if (isNaN(h)) {
    return "&infin;"
  }
  return h + ':' + s
}
//监听audio当前播放位置
const asss = () => {
  const currentTime = audioRef.value.currentTime.toFixed(1) - 0;
  const arr = stroe.state.lyric;
  for (let i = 0; i < arr.length; i++) {
    if (currentTime > arr[i].time) {
      stroe.commit('SHOW_FECI', i)
    }
  }

}

</script>

<style lang="scss" scoped>
.container_center {
  span {
    margin: 0 1rem;
  }

}

.buutton {
  margin: 0.5rem 0.5rem;
}

.receptacle {
  text-align: center;
}
</style>